<template lang="pug">
     el-card
        div(slot="header" class="clearfix")
            div(class="pull-right")
                el-button(type="primary" @click="saveRoles") 保存 
        el-table(:data="roles" @selection-change="onselect" ref="roleTable")
                el-table-column(type="selection")
                el-table-column(prop="name" label="角色")
</template>
<script>
import _axios from '@/plugin/axios'
export default {
    name : 'role-panel',
    data () {
        return {
            roles: [],

            selectedRows: []
        };
    },

    props: {
        userId: { type: String }
    },

    watch: {
        userId: function () {
            this.getRolesByUser();
        }
    },

    methods: {
        getRolesByUser: function () {
            var data = { userId: this.userId };
            var options = {
                url: '/user/getRolesByUser', method: 'post', data: data
            };

            var vm = this;
            _axios(options).then(function (res) {
                vm.roles = res;
                vm.checkRow();
            });
        },

        onselect: function (rows) {
            this.selectedRows = rows; // 选中的数据缓存起来
        },

        // 解析出有权限和没权限的数据
        resolveIsInRole: function () {
            if (!this.roles.length) return;

            for (var index2 = 0; index2 < this.roles.length; index2++) {
                var role = this.roles[index2];

                var isInRole = false;
                for (var index = 0; index < this.selectedRows.length; index++) {
                    var row = this.selectedRows[index];


                    if (role.id !== row.id) continue;
                    isInRole = true;
                    break;
                }
                role.isInRole = isInRole; // 把数据设置为
            }
        },

        checkRow: function () {
            if (!this.roles.length) return;
            var vm = this;
            this.$nextTick(function () {

                for (var index2 = 0; index2 < this.roles.length; index2++) {
                    var role = this.roles[index2];
                    var checked = role.isInRole;


                    vm.$refs.roleTable.toggleRowSelection(role, checked);
                }
            });

        },

        saveRoles: function () {
            this.resolveIsInRole(); // 解析出有权限和没权限的数据

            var data = { models: this.roles };

            var options = { url: '/user/SaveRoles', method: 'post', data: data };

            _axios(options).then(res => { this.$message.success('保存成功') });
        }
    },

    created(){
        if(this.userId) this.getRolesByUser();
    }
}
</script>